<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 订单商品生产类
 * @package  module/base/bill
 * @author   allen.qiang
 * @version 1.0
 */

class billProduct {

    /**
     * 查询订单商品生产表信息
     * @param array $arg_array
     * @return null|array
     */
    public function searchBillProductGoods( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && !empty($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //订单编号
        if (isset($arg_array['bill_code']) && !empty($arg_array['bill_code'])) {
            $sql .= ' AND bill_code LIKE ? ';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['bill_code'] . '%';
        }

        //订单商品流水号
        if (isset($arg_array['bill_goods_no']) &&  !empty($arg_array['bill_goods_no'])) {
            $sql .= ' AND bill_goods_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_goods_no'];
        }

        //城市ID
        if (isset($arg_array['cityID']) && !empty($arg_array['cityID'])) {
            $sql .= ' AND cityID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityID'];
        }

        //订单类型
        if(isset($arg_array['bill_type']) && !empty($arg_array['bill_type'])){
            if(strpos($arg_array['bill_type'],'all') !== false){
                $sql .= " AND billType IN (1,2,3,4,5,6)";
            }else{
                $sql .= " AND billType IN ( ".$arg_array['bill_type']." )";
            }
        }

        //配送日期
        if (isset($arg_array['send_date']) && !empty($arg_array['send_date'])) {
            $sql .= ' AND send_date = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['send_date'];
        }

        //配送开始时间
        if (isset($arg_array['send_start_time']) && !empty($arg_array['send_start_time'])) {
            $sql .= ' AND send_start_time >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['send_start_time'];
        }

        //配送结束时间
        if (isset($arg_array['send_start_time_end']) && !empty($arg_array['send_start_time_end'])) {
            $sql .= ' AND send_start_time <= ?  ';
            $params_type .= 's';
            $params_array[] = $arg_array['send_start_time_end'];
        }

        //配送站ID
        if (isset($arg_array['distribution_id']) && !empty($arg_array['distribution_id'])) {
            $sql .= ' AND distribution_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['distribution_id'];
        }

        //配送站名称
        if (isset($arg_array['distribution_name']) && !empty($arg_array['distribution_name'])) {
            $sql .= ' AND distribution_name = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['distribution_name']);
        }

        //商家编码
        if (isset($arg_array['product_code']) && !empty($arg_array['product_code'])) {
            $sql .= ' AND product_code = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['product_code'];
        }

        //商品名称 /SKU / 商品ID  模糊查询
        if (isset($arg_array['sku']) && !empty($arg_array['sku'])) {
            $sql .= ' AND (goods_name LIKE ? OR product_code =? OR goods_postID = ?) ';
            $params_type .= 'ssi';
            $params_array[] = '%' . $arg_array['sku'] . '%';
            $params_array[] = $arg_array['sku'];
            $params_array[] = $arg_array['sku'];
        }

        //生日牌
        if (isset($arg_array['birthday_card']) && is_numeric($arg_array['birthday_card'])) {
            if($arg_array['birthday_card'] == 1){ //状态为是 含生日牌
                $sql .= ' AND birthday_card IS NOT NULL AND birthday_card <> "" ';
            }else{
                $sql .= ' AND birthday_card = "" ';
            }
        }

        //切分状态
        if (isset($arg_array['segmentation']) && is_numeric($arg_array['segmentation'])) {
            if($arg_array['segmentation'] == 1){ //状态为是 切分
                $sql .= ' AND segmentation >= ?';
            }else{
                $sql .= ' AND segmentation = ?';
            }
            $params_type .= 'i';
            $params_array[] = $arg_array['segmentation'];

        }

        //是否打印
        if (isset($arg_array['print_num']) && is_numeric($arg_array['print_num'])) {
            if($arg_array['print_num'] == 1){ //状态为是 打印
                $sql .= ' AND print_num >= ?';
            }else{
                $sql .= ' AND print_num = ?';
            }
            $params_type .= 'i';
            $params_array[] = $arg_array['print_num'];

        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

            //统计数量
            $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_goods_product ' . $sql;

            $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);


            $item_count = $count_array[0]->item_count;
            if ($item_count == 0) {
                $arg_array['count'] = 0;
                return null;
            }

            $arg_array['count'] = $item_count;

            if($_REQUEST['count'] < $_REQUEST['rp']){
                $_REQUEST['page'] = 1;
            }

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            //分页
            if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                $arg_array['page'] = 1;

            $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

        } else {

            //排序
            if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

        }

        //查询分类信息
        $search_sql = 'SELECT * FROM bill_goods_product' . $sql;
        $temp_item_array = $G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
        if (!$temp_item_array) {
            return null;
        }

        $item_array = array();

        foreach ($temp_item_array as $bill) {

            $item_array[] = array(

                'uuid' => $bill->uuid,
                'creator' => $bill->creator,
                'createTime' => $bill->createTime,
                'bill_no' => (string)$bill->bill_no,
                'bill_code' => (string)$bill->bill_code,
                'bill_goods_no' => (string)$bill->bill_goods_no,
                'cityID' => $bill->cityID,
                'cityName' => $bill->cityName,
                'billType' => $bill->billType,
                'send_date' => $bill->send_date,
                'send_start_time' => $bill->send_start_time,
                'send_end_time' => $bill->send_end_time,
                'distribution_id' => $bill->distribution_id,
                'distribution_name' => $bill->distribution_name,
                'is_urgent' => $bill->is_urgent,
                'goods_postID' => $bill->goods_postID,
                'product_code' => $bill->product_code,
                'goods_name' => $bill->goods_name,
                'goods_spec' => $bill->goods_spec,
                'goods_amount' => $bill->goods_amount,

                'tableware_amount' => $bill->tableware_amount,
                'extra_tableware_amount'=>$bill->extra_tableware_amount,
                'candle_amount'=>$bill->candle_amount,
                'extra_candle_amount'=>$bill->extra_candle_amount,

                'birthday_card' => $bill->birthday_card,
                'segmentation' => $bill->segmentation,
                'goods_remark' => $bill->goods_remark,
                'print_num' => $bill->print_num,
                'print_operator' => $bill->print_operator,
                'print_time' => $bill->print_time



            );
        }

        return $item_array;

    }

    /**
     * 查询订单商品生产详情
     * @param int $bill_goods_no 商品流水号
     * @return null|array
     */
    public function searchBillProductGoodsDetail( $bill_goods_no ) {

        if (!isset($bill_goods_no) || empty($bill_goods_no)) {
            return null;
        }

        $args_array = array(
            'bill_goods_no' => $bill_goods_no
        );
        $bill_product_goods_array = $this->searchBillProductGoods( $args_array );
        if ($bill_product_goods_array) {
            return $bill_product_goods_array[0];
        } else {
            return null;
        }

    }

    /**
     * 打印订单商品
     * @param $bill_goods_array
     * @return array
     */
    public function printGoodsQs( $bill_goods_array ) {

        global $G_SHOP;

        quanli_include('module/base/common/quanliLog.class.php');
        quanli_include('module/base/bill/billEdit.class.php');

        //实例日志类
        $quanliLog = new quanliLog();

        //实例订单编辑类
        $billEdit = new billEdit( $G_SHOP->DBCA );

        try {

            foreach($bill_goods_array as &$bill_goods_no) {

                $G_SHOP->DBCA->beginTransaction();

                /**
                 * ========================================
                 * 增加订单商品生产表bill_goods_product添加打印信息
                 * ========================================
                 */
                $bill_goods_product = new entity('bill_goods_product');
                $bill_goods_product ->bill_goods_no = $bill_goods_no;
                if (!$G_SHOP->DBCA->fetch($bill_goods_product)) {
                    throw new Exception( '商品流水号[' . $bill_goods_no. ']，商品不存在<br>商品生产状态更新失败' , 404 );
                }
                $bill_goods_product->print_num = $bill_goods_product->print_num + 1; //打印次数+1
                $bill_goods_product->print_operator = $G_SHOP->currentUserID;
                $bill_goods_product->print_time = $G_SHOP->sys_datetime;
                $G_SHOP->DBCA->save($bill_goods_product);
                /**
                 * ========================================
                 * 增加订单商品生产表bill_goods_product添加打印信息
                 * ========================================
                 */


                /**
                 * ========================================
                 * 增加订单商品表bill_goods添加打印信息
                 * ========================================
                 */
                $bill_goods = new entity('bill_goods');
                $bill_goods ->bill_goods_no = $bill_goods_no;
                if (!$G_SHOP->DBCA->fetch($bill_goods)) {
                    throw new Exception( '商品流水号[' . $bill_goods_no. ']，商品不存在<br>商品生产状态更新失败' , 404 );
                }
                $bill_goods->print_num = $bill_goods->print_num + 1; //打印次数+1
                $bill_goods->print_operator = $G_SHOP->currentUserID;
                $bill_goods->print_time = $G_SHOP->sys_datetime;
                $G_SHOP->DBCA->save($bill_goods);
                /**
                 * ========================================
                 * 增加订单商品表bill_goods添加打印信息
                 * ========================================
                 */




                /**
                 * ========================================
                 * 打印改变订单主表订单状态
                 * ========================================
                 */
                $bill_master = new entity('bill_master');
                $bill_master->bill_no = $bill_goods->bill_no;
                if (!$G_SHOP->DBCA->fetch($bill_master)) {
                    throw new Exception( '订单[' . $bill_goods_product->bill_code . ']不存在<br>商品生产状态更新失败' , 404 );
                }
                if ($bill_master->bill_status == 0) {
                    throw new Exception( '订单[' . $bill_goods_product->bill_code . ']未审核<br>商品生产状态更新失败' , 404 );
                }

                if ($bill_goods->print_num == 1) {

                    //判断订单商品总数量 与 订单商品生产总数量 相等 订单商品已生产
                    if( $bill_master->bill_totalAmount > $bill_master->bill_product_amount ){
                        $bill_master->bill_product_amount = $bill_master->bill_product_amount + 1; //打印时订单商品生产数量+1
                    }

                    if ($bill_master->bill_totalAmount == $bill_master->bill_product_amount && $bill_master->bill_status == 1) {
                        $bill_master->bill_status = 2; //状态为生产'
                    }

                    $G_SHOP->DBCA->save( $bill_master );

                }


                /**
                 * ========================================
                 * 打印改变订单主表订单状态end
                 * ========================================
                 */

                /*=======================================================
                 * 写入日志
                 * ======================================================
                 */
                //订单状态
                if ($bill_goods->print_num == 1) {

                    $log_array = array(
                        'logCategoryID' => 1,
                        'logItem' => $bill_master->bill_no,
                        'extend_1' => $bill_master->bill_status == 2 ? '订单已生产' : '',
                        'extend_2' => $bill_goods_no . ' ' . $bill_goods_product->goods_name .'，已生产',
                        'extend_5' => $bill_master->bill_status,
                        'operator' => $G_SHOP->currentUserName
                    );

                    if ($bill_master->bill_status == 2) {

                        //保存订单轨迹
                        $bill_no = $bill_master->bill_no;
                        $operator = $G_SHOP->currentUserID;
                        $content = '您的订单已生产';
                        $billEdit = new billEdit( $G_SHOP->DBCA);
                        $billTrace = $billEdit->addBillTrace( $bill_no, $operator, $content );
                        if ( !$billTrace ){
                            throw new Exception( '订单轨迹保存失败', 400);
                        }

                    }

                } else {

                    $log_array = array(
                        'logCategoryID' => 1,
                        'logItem' => $bill_master->bill_no,
                        'extend_1' => '',
                        'extend_2' => $bill_goods_no . ' ' . $bill_goods_product->goods_name . '，重复生产',
                        'extend_5' => $bill_master->bill_status,
                        'operator' => $G_SHOP->currentUserName
                    );

                }

                $result_array = $quanliLog->saveLogInfo( $log_array );
                if ($result_array['code'] != 200) {
                    throw new Exception( $result_array['message'], $result_array['code']);
                }

                $G_SHOP->DBCA->commit();

            }


            return array( 'code' => 200, 'message' => '打印成功' );

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log('订单商品生产打印：' . $e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

}